<?php


namespace logic\cyf;


use frontend\models\cyf\MemberRule;
use frontend\models\cyf\User;

class VipLogic
{
    /**
     * 查看用户特权
     * @param $uid
     * @name cyf
     */
    public static function detail($uid)
    {
        $user = User::getOneUserById($uid);//查看用户信息
        if(!$user) throw new \Exception('用户不存在，请先注册');
        $rule_id = $user['member']['id'];//得到会员等级
        $rule = MemberRule::getRuleByCardId($rule_id);//查看会员权益
        $data['user'] = $user;
        $data['rule'] = $rule;
        return $data;
    }

    /**
     * 降级逻辑
     * @param $uid
     * @return bool
     * @throws \Exception
     * @name cyf
     */
    public static function downGrad($uid)
    {
        $user = User::getOneUserById($uid);
        $registration_time = $user['registration_time'];//获取注册时间
        $time = strtotime("+1 year",strtotime($registration_time));//一年后时间戳
        $newTime = date('Y-m-d H:i:s',$time);//一年后时间
        if(date('Y-m-d H:i:s') < $newTime) throw new \Exception('没到更新时间哦');
        if($user['membership'] == 1)  throw new \Exception('不需要降级');
        $res = User::downGrad($uid);
        if(!$res) return false;
        return  true;
    }

    /**
     * 增加积分
     * @param $params
     * @return bool|void
     * @throws \Exception
     * @name cyf
     */
    public static function getIntegral($params)
    {
        $transaction = \Yii::$app->db->beginTransaction();
        $bool = User::upScore($params);
        if(!$bool){
            $transaction->rollBack();
            throw new \Exception('加分失败');
        }
        $user = User::getOneUserById($params['uid']);
        //添加积分来源

        $res = self::is_grade($user['membership'],$user['member'],$params['uid']);
        $transaction->commit();
        return $res;
    }
    /**
     * 判断用户是否达到升级标准
     * @param $grade
     * @param $fen
     * @param $uid
     * @return bool|void
     * @name cyf
     */
    public static function is_grade($grade,$fen,$uid)
    {
        switch ($grade){
            case $grade == 1 && $fen>=2000 : $res =User::upgrade($uid,2000);break;
            case $grade == 2 && $fen>=3000 : $res =User::upgrade($uid,3000);break;
            case $grade == 3 && $fen>=4000 : $res =User::upgrade($uid,4000);break;
            case 4 : return true; break;
            default : return '没有达到升级标准哦'; break;
        }
        return $res;

    }
}